package com.bai.ad.index;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ClassName DataTable
 *
 * @author Bai
 * @version 1.0
 * @date 2019/2/28 0028 下午 22:59
 **/
@Slf4j
@Component
public class DataTable implements ApplicationContextAware, PriorityOrdered {

    private static ApplicationContext applicationContextl;

    private static final Map<Class, Object> dataTableMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DataTable.applicationContextl = applicationContext;
    }


    @Override
    public int getOrder() {
        // 设置组件加载的顺序
        return PriorityOrdered.HIGHEST_PRECEDENCE;
    }

    @SuppressWarnings("all")
    public static <T> T of(Class<T> clazz){
        T instance = (T) dataTableMap.get(clazz);
        if(null != instance){
            return instance;
        }
        dataTableMap.put(clazz, bean(clazz));
        return (T) dataTableMap.get(clazz);
    }

    @SuppressWarnings("all")
    private static <T> T bean(String beanName){
        return (T) applicationContextl.getBean(beanName);
    }

    @SuppressWarnings("all")
    private static <T> T bean(Class clazz){
        return (T) applicationContextl.getBean(clazz);
    }
}
